<!-- 进程管控 -->
<template>
  <div>
    <el-row>
      <div style="display:flex;align-items: center;margin-bottom:15px;">
        <div style="min-width:90px;color:#606266;font-size:14px;">默认策略<span style="color:#f36b6e;font-size:20px;padding-left:10px;">
            <el-tooltip class="item" effect="dark" placement="right">
              <i class="el-icon-question"></i>
              <div style="width: 600px;" slot="content">（默认策略指定是不在规则列表中的访问行为。该默认策略影响网络准入规则和开放端口策略）</div>
            </el-tooltip>
          </span>：</div>
        <div>
          <el-radio v-model="DefaultPolicy" :label="1" @change="radioChange">放行</el-radio>
          <el-radio v-model="DefaultPolicy" :label="2" @change="radioChange">阻断</el-radio>
          
        </div>
      </div>
      <div style="display:flex;justify-content:space-between;">
        <div>
          <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addClick()">添加规则</el-button>
          <span style="color:#d2d7e3;font-size:25px;margin-top:10px;padding-left:10px;">
            <el-tooltip class="item" effect="dark" placement="right">
              <i class="el-icon-question"></i>
              <div style="width: 420px;" slot="content">通过拖动表格行来重新排列顺序,
                系统按次序从上到下优先级执行。终端找到一条匹配的规则后将不再向下继续匹配规则。匹配不到规则将使用默认策略。通过拖动表格行来重新排列顺序,
                系统按次序从上到下优先级执行。添加放到所有规则最后，插入表示在当前策略前插入一条规则</div>
            </el-tooltip>
          </span>
        </div>
      </div>
      <el-table stripe border :data="tableData" class="draggable-table" table-id="table1" row-key="RuleName"
        style="width: 100%; margin-top: 15px">
        <el-table-column label="序号" width="60" type="index"
          :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
        <el-table-column label="规则名称" prop="RuleName" show-overflow-tooltip width="160px"></el-table-column>
        <el-table-column label="规则状态" show-overflow-tooltip prop="IsValid" width="160px">
          <template slot-scope="{row}">
            <span style="color:#67C23A" v-if="row.IsValid === 1" type="success">正常</span>
            <span style="color:#F56C6C" v-else type="danger">失效</span>
          </template>
        </el-table-column>
        <el-table-column label="控制策略" show-overflow-tooltip prop="Policy" width="120px">
          <template slot-scope="{row}">
            <span>{{ row.Policy === 1 ? '放行' : '阻断' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="协议类型" show-overflow-tooltip prop="Protocol" width="120px"></el-table-column>
        <el-table-column label="源对象类型" show-overflow-tooltip prop="SrcDeviceObjType" width="160px"
          :formatter="SrcDeviceObjTypeFormatter"></el-table-column>
        <el-table-column label="源对象" show-overflow-tooltip prop="SrcDeviceObj" width="160px"
          :formatter="SrcDeviceObjFormatter">
          <template slot-scope="{row}">
            <span>{{ SrcDeviceObjFormatter(row, DepartmentList, AssetsListMap) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="目的类型" show-overflow-tooltip prop="DstDeviceObjType" width="160px"
          :formatter="DeviceObjTypeFormatter"></el-table-column>
        <el-table-column label="目的对象" show-overflow-tooltip prop="DstDeviceObj" width="160px"
          :formatter="DeviceObjFormatter">
          <template slot-scope="{row}">
            <span>{{ DeviceObjFormatter(row, DepartmentList, AssetsListMap) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="目的端口" show-overflow-tooltip prop="DstPort" width="160px">
          <template slot-scope="{row}">
            <span>{{ row.DstPortType === 1 ? '全部' : row.DstPort }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注信息" show-overflow-tooltip prop="Descp"></el-table-column>
        <el-table-column label="操作" fixed="right" width="220px">
          <template slot-scope="scope">
            <el-button size="mini" type="success" @click="insertClick(scope.row, scope.$index)">插入</el-button>
            <el-button size="mini" type="primary" @click="changeClick(scope.row, scope.$index)">修改</el-button>
            <el-button size="mini" type="danger" @click="deleteClick(tableData, scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-dialog top="5vh" :close-on-click-modal="false" :close-on-press-escape=false
      :title="Action === 1 ? '添加规则'  : Action === 2 ? '修改规则' : '插入规则'" :visible.sync="dialogVisible" @close="getData()" v-el-drag-dialog
      width="1000px">
      <el-form label-width="130px" :model="accountForm" :rules="rules" ref="accountForm">
        <el-row class="ruleMain">
          <el-divider content-position="left">规则基本内容</el-divider>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='规则名称：' prop="RuleName">
              <el-input v-model.trim="accountForm.RuleName" :disabled="Action === 2" :maxlength="30"></el-input>
            </el-form-item>
            <el-form-item label='规则状态：' prop="IsVaclid">
              <el-radio v-model="accountForm.IsValid" :label="1">正常</el-radio>
              <el-radio v-model="accountForm.IsValid" :label="0">失效</el-radio>
            </el-form-item>
            <el-form-item label='控制策略：' prop="Policy">
              <el-select style="width:100%" v-model="accountForm.Policy" placeholder="请选择控制策略">
                <el-option label="放行" :value="1"></el-option>
                <el-option label="阻断" :value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label='协议类型：' prop="Protocol">
              <el-select style="width:100%" v-model="accountForm.Protocol" placeholder="请选择协议类型">
                <el-option label="ANY" value="ANY"></el-option>
                <el-option label="TCP" value="TCP"></el-option>
                <el-option label="UDP" value="UDP"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label='源地址对象：' prop="SrcDeviceObjType">
              <el-radio v-model="accountForm.SrcDeviceObjType" @change="DeviceObjTypeChange" :label="1">全部</el-radio>
              <el-radio v-model="accountForm.SrcDeviceObjType" @change="DeviceObjTypeChange" :label="2">指定部门</el-radio>
              <el-radio v-model="accountForm.SrcDeviceObjType" @change="DeviceObjTypeChange" :label="8">指定角色</el-radio>
              <el-radio v-model="accountForm.SrcDeviceObjType" @change="DeviceObjTypeChange" :label="6">指定资产</el-radio>
              <el-radio v-model="accountForm.SrcDeviceObjType" @change="DeviceObjTypeChange" :label="7">指定地址或网段</el-radio>
              <el-cascader v-if="accountForm.SrcDeviceObjType === 2" :disabled="accountForm.SrcDeviceObjType === 1"
                multiple style="width:100%;"
                :placeholder="`${accountForm.SrcDeviceObjType === 1 ? '全部' : accountForm.SrcDeviceObjType === 2 ? '请选择部门' : '请选择资产'}`"
                ref="cascaderAddr" v-model="accountForm.SrcDeviceObj" clearable :options="DeviceObjList"
                :props="{ children: 'Children', expandTrigger: 'hover', label: 'Name', value: 'ID', emitPath: false, multiple: true, checkStrictly: accountForm.SrcDeviceObjType === 2 ? true : false }">
              </el-cascader>
              <el-select v-if="accountForm.SrcDeviceObjType === 8" style="width:100%" v-model="accountForm.SrcDeviceObj"
                multiple placeholder="请选择角色">
                <el-option v-for="(item, index) in RoleList" :key="index" :label="item.Role"
                  :value="item.Role"></el-option>
              </el-select>
              <el-input v-if="accountForm.SrcDeviceObjType === 7" placeholder="请输入请输入地址或网段,需符合下面的规则，多个对象用回车分割
eg. 192.168.0.1; 192.168.0.1; [fc00::]
eg. 192.168.0.1:80; 192.168.0.1:443; [fc00::]:443;
eg. 192.168.0.1-192.168.0.255; 192.168.0.1-192.168.0.255;
eg. 192.168.0.1-192.168.0.255:80; 192.168.0.1-192.168.0.255:443;
eg. 192.168.0.0/16; 192.168.0.0/24; fe80::/10;
eg. 20-21; 49152-65534;
eg. 21; 80; 443" type="textarea" :rows="5" v-model="accountForm.SrcDeviceObj"></el-input>
              <el-cascader v-if="accountForm.SrcDeviceObjType === 6" style="width:100%;" placeholder="请选择资产"
                ref="cascaderAddr" v-model="accountForm.SrcDeviceObj" :options="AssetsList" :props="{
                  children: 'Children',
                  expandTrigger: 'hover',
                  label: 'Name',
                  value: 'ID',
                  emitPath: false,
                  multiple: true,
                  checkStrictly: false,
                }" />
            </el-form-item>
            <el-form-item label='应用对象：' prop="DstDeviceObjType">
              <el-radio v-model="accountForm.DstDeviceObjType" @change="DeviceObjTypeChange2" :label="1">全部</el-radio>
              <el-radio v-model="accountForm.DstDeviceObjType" @change="DeviceObjTypeChange2" :label="2">指定部门</el-radio>
              <el-radio v-model="accountForm.DstDeviceObjType" @change="DeviceObjTypeChange2" :label="8">指定角色</el-radio>
              <el-radio v-model="accountForm.DstDeviceObjType" @change="DeviceObjTypeChange2" :label="6">指定资产</el-radio>
              <el-cascader v-if="accountForm.DstDeviceObjType === 2" :disabled="accountForm.DstDeviceObjType === 1"
                multiple style="width:100%;"
                :placeholder="`${accountForm.DstDeviceObjType === 1 ? '全部' : accountForm.DstDeviceObjType === 2 ? '请选择部门' : '请选择资产'}`"
                ref="cascaderAddr" v-model="accountForm.DstDeviceObj" clearable :options="DeviceObjList"
                :props="{ children: 'Children', expandTrigger: 'hover', label: 'Name', value: 'ID', emitPath: false, multiple: true, checkStrictly: accountForm.DstDeviceObjType === 2 ? true : false }">
              </el-cascader>
              <el-select v-if="accountForm.DstDeviceObjType === 8" style="width:100%" v-model="accountForm.DstDeviceObj"
                multiple placeholder="请选择角色">
                <el-option v-for="(item, index) in RoleList" :key="index" :label="item.Role"
                  :value="item.Role"></el-option>
              </el-select>
              <el-cascader v-if="accountForm.DstDeviceObjType === 6" style="width:100%;" placeholder="请选择资产"
                ref="cascaderAddr" v-model="accountForm.DstDeviceObj" :options="AssetsList" :props="{
                  children: 'Children',
                  expandTrigger: 'hover',
                  label: 'Name',
                  value: 'ID',
                  emitPath: false,
                  multiple: true,
                  checkStrictly: false,
                }" />
            </el-form-item>
            <el-form-item label='目的端口：' prop="DstDeviceObjType">
              <el-radio v-model="accountForm.DstPortType" :label="1">全部</el-radio>
              <el-radio v-model="accountForm.DstPortType" :label="2">指定端口</el-radio>
              <el-input v-if="accountForm.DstPortType === 2" oninput="value=value.replace(/[^0-9-;]/g,'')"
                v-model="accountForm.DstPort" placeholder="请输入端口或端口段，例：1-65535，22;443"></el-input>
            </el-form-item>
            <el-form-item label="备注信息：" prop="Descp">
              <el-input placeholder="请输入备注" type="textarea" maxlength="50" :rows="3"
                v-model="accountForm.Descp"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false; getData()">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { connrequest } from '@/api/firstPage'
import { validateInput, transformToCascaderTree, validatePort } from "@/utils/index.js";
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import Sortable from "sortablejs";
export default {
  directives: { elDragDialog },
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      tableData: [],
      DefaultPolicy: 1,
      RoleList: [],
      DepartmentList: [],
      AssetsList: [],
      AssetsListMap: [],
      DeviceObjList: [],
      Action: 0,
      dialogVisible: false,
      accountForm: {},
      auditAction: 1,
      auditdialog: false,
      auditForm: {
        Protocol: 'ANY',
        IsValid: 1,
        Policy: 1,
        SrcDeviceObjType: 1,
        DstDeviceObjType: 1,
        DstPortType: 1
      },
      OBJList: '',
      rules: {
        RuleName: [
          { required: true, message: "请输入规则名称" }
        ],
      },
    }
  },
  watch: {
    Action() {
      this.$nextTick(() => {
        this.initSort()
      })
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.initSort();
    this.GetDepartmentDeviceSumTree()
    this.GetDepartment()
    this.GetRolestatus()
    this.initData()
  },
  methods: {
    validatePort(value) {
      this.$set(this.accountForm, 'DstPort', validatePort(value))
    },
    initSort() {
      document.querySelectorAll('.draggable-table').forEach(table => {
        const el = table.querySelector('.el-table__body-wrapper > table > tbody');
        const tableId = table.getAttribute('table-id');
        new Sortable(el, {
          animation: 500,
          onEnd: async (evt) => {
            if (tableId === 'table1') {
              const currRow = this.tableData.splice(evt.oldIndex, 1)[0];
              this.tableData.splice(evt.newIndex, 0, currRow);
              const newData = [];
              this.tableData.forEach((item, index) => {
                newData[index] = {
                  id: item.id,
                  rank: index + 1
                };
              });
              const data = {
                Filter: {
                  FileName: 'rule_net_in.json'
                },
                Data: {
                  DefaultPolicy: this.DefaultPolicy,
                  RuleData: [...this.tableData]
                }
              };
              const res = await connrequest('SetUICommonParam', data);
              if (res.Status.StatusCode === 0) {
                this.$message.success('排序成功');
                this.getData();
              }
            }
          }
        });
      });
    },
    SrcDeviceObjTypeFormatter(row) {
      switch (row.SrcDeviceObjType) {
        case 1:
          return '全部'
          break;
        case 2:
          return '指定部门'
          break;
        case 8:
          return '指定角色'
          break;
        case 6:
          return '指定资产'
          break;
        default:
          return '指定地址或网段'
          break;
      }
    },
    SrcDeviceObjFormatter(row = {}, departments = [], assets = []) {
      const { SrcDeviceObjType, SrcDeviceObj = [] } = row;
      if (SrcDeviceObjType === 1) return '全部';
      else if (SrcDeviceObjType === 2) {
        const deptNames = SrcDeviceObj.map(id => {
          const dept = departments.find(d => d.ID === id);
          return dept ? dept.DepartmentName : '未知部门';
        });
        return deptNames.join(', ');
      } else if (SrcDeviceObjType === 8) {
        if (!SrcDeviceObj) {
          return ''
        }
        return SrcDeviceObj.join(', ');
      } else if (SrcDeviceObjType === 7) {
        if (!SrcDeviceObj) {
          return ''
        }
        return SrcDeviceObj.join(', ');
      } else if (SrcDeviceObjType === 6) {
        const assetNames = SrcDeviceObj.map(uuid => {
          const asset = assets.find(a => a.DeviceUUID === uuid);
          return asset ? asset.DeviceName : '未知资产';
        });
        return assetNames.join(', ');
      }
      return '未知类型';
    },
    DeviceObjTypeFormatter(row) {
      switch (row.DstDeviceObjType) {
        case 1:
          return '全部'
          break;
        case 2:
          return '指定部门'
          break;
        case 8:
          return '指定角色'
          break;
        default:
          return '指定资产'
          break;
      }
    },
    DeviceObjFormatter(row = {}, departments = [], assets = []) {
      const { DstDeviceObjType, DstDeviceObj = [] } = row;
      if (DstDeviceObjType === 1) return '全部';
      else if (DstDeviceObjType === 2) {
        if (!row.DstDeviceObj) {
          return '未知部门'
        }
        const deptNames = DstDeviceObj.map(id => {
          const dept = departments.find(d => d.ID === id);
          return dept ? dept.DepartmentName : '未知部门';
        });
        return deptNames.join(', ');
      } else if (DstDeviceObjType === 8) {
        return DstDeviceObj.join(', ');
      } else if (DstDeviceObjType === 6) {
        if (!row.DstDeviceObj) {
          return '未知资产'
        }
        const assetNames = DstDeviceObj.map(uuid => {
          const asset = assets.find(a => a.DeviceUUID === uuid);
          return asset ? asset.DeviceName : '未知资产';
        });
        return assetNames.join(', ');
      }
      return '未知类型';
    },
    getNamesByDeviceIds(treeData, deviceIds, defaultName = '未知设备') {
      // 如果 deviceIds 不是数组或为空，返回默认值
      if (!Array.isArray(deviceIds) || deviceIds.length === 0) {
        return defaultName;
      }
      // 将树结构扁平化，提取所有设备节点
      const deviceMap = new Map();
      treeData.forEach(dept => {
        if (dept.Children && dept.Children.length > 0) {
          dept.Children.forEach(device => {
            deviceMap.set(device.ID, device.Name);
          });
        }
      });
      // 根据 deviceIds 获取对应的 Name，未找到时使用默认值
      const names = deviceIds.map(id => deviceMap.get(id) || defaultName);

      // 返回逗号分隔的字符串
      return names.join(',');
    },
    async GetDictProcess() {
      const res = await connrequest('GetDictProcess')
      this.OBJList = res.Data
    },
    async getData() {
      const data = {
        Filter: {
          FileName: 'rule_net_in.json'
        }
      }
      const res = await connrequest('GetUICommonParam', data)
      this.DefaultPolicy = res.Data?.DefaultPolicy || 1
      this.tableData = res.Data?.RuleData || []
    },
    async DeviceObjTypeChange(value) {
      this.$set(this.accountForm, 'SrcDeviceObj', '')
      if (value === 0) {
        this.DeviceObjList = []
      } else if (value === 2) {
        await this.GetDepartmentDeviceSumTree()
      } else if (value === 7) {

      } else if (value === 8) {
        await this.GetRolestatus()
      } else {
        await this.initData()
      }
    },
    async DeviceObjTypeChange2(value) {
      this.$set(this.accountForm, 'DstDeviceObj', '')
      if (value === 0) {
        this.DeviceObjList = []
      } else if (value === 2) {
        await this.GetDepartmentDeviceSumTree()
      } else if (value === 8) {
        await this.GetRolestatus()
      } else {
        await this.initData()
      }
    },
    // 获取资产树
    async initData(searchobj = {}) {
      try {
        // 获取部门数据
        const deptResponse = await connrequest('GetDepartmentDeviceSumTree')
        const departments = deptResponse.Data.Department
        // 获取所有设备数据
        const data = {
          Paging: {
            QueryPageNo: 1,
            QueryPageLength: 100000
          }
        }
        const deviceResponse = await connrequest('GetDevice', data)
        const devices = deviceResponse.Data

        // 生成树结构
        this.AssetsList = this.initDeviceTree(departments, devices)
        this.AssetsListMap = devices

      } catch (error) {
        console.error('初始化数据失败:', error)
      }
    },
    // 将设备数据转换为 el-cascader 树结构的函数
    initDeviceTree(departments, devices) {
      let deviceObjList = []
      // 创建部门映射表
      const departmentMap = new Map();
      const departmentClones = departments.map(dept => ({
        ...dept,
        Children: []
      }));
      // 建立父子关系
      departmentClones.forEach(dept => {
        departmentMap.set(dept.ID, dept);
        if (dept.ParentID === 0) {
          deviceObjList.push(dept);
        } else {
          const parent = departmentMap.get(dept.ParentID);
          parent && parent.Children.push(dept);
        }
      });
      // 将设备挂载到对应部门
      devices.forEach(device => {
        const dept = departmentMap.get(device.DepartmentID);
        if (dept) {
          dept.Children.push({
            ...device,
            ID: device.DeviceUUID,
            Name: device.DeviceName || device.DeviceCode || '未命名设备',
            Children: null,
            leaf: false,
            isDevice: true
          });
        }
      });
      // 递归过滤空部门
      const filterEmptyDepartments = (nodes) => {
        return nodes.filter(node => {
          // 保留设备节点
          if (node.isDevice) return true;
          // 递归过滤子节点
          if (node.Children) {
            node.Children = filterEmptyDepartments(node.Children);
          }
          // 保留有子节点（部门或设备）的部门
          return node.Children && node.Children.length > 0;
        });
      };
      deviceObjList = filterEmptyDepartments(deviceObjList)
      return deviceObjList
    },
    // 获取部门树
    async GetDepartmentDeviceSumTree() {
      const res = await connrequest('GetDepartmentDeviceSumTree')
      const deviceObjList = transformToCascaderTree(res.Data.Department)
      this.DeviceObjList = deviceObjList
    },
    // 获取所有部门
    async GetDepartment() {
      const res = await connrequest('GetDepartment')
      this.DepartmentList = res.Data
    },
    // 获取角色
    async GetRolestatus() {
      const res = await connrequest('GetParamDictRole')
      this.RoleList = res.Data
    },
    addClick() {
      this.Action = 1;
      this.$nextTick(() => {
        // 等待组件挂载
        this.accountForm = {
          Protocol: 'ANY',
          IsValid: 1,
          Policy: 1,
          SrcDeviceObjType: 1,
          DstDeviceObjType: 1,
          DstPortType: 1,
        };
        this.$refs['accountForm'].resetFields();
      });
      this.dialogVisible = true;
    },
    insertClick(row, index) {
      this.Action = 3
      this.tableindex = index
      this.$nextTick(() => {
        // 等待组件挂载
        this.accountForm = {
          Protocol: 'ANY',
          IsValid: 1,
          Policy: 1,
          SrcDeviceObjType: 1,
          DstDeviceObjType: 1,
          DstPortType: 1
        };
        this.$refs['accountForm'].resetFields();
      });
      this.dialogVisible = true;
    },
    changeClick(row, index) {
      this.DeviceObjTypeChange(row.DeviceObjType)
      this.tableindex = index
      this.Action = 2
      this.$nextTick(() => {
        this.accountForm = { ...row, ProcObjs: row.ProcObjs, SrcDeviceObj: row.SrcDeviceObjType === 7 ? row.SrcDeviceObj.join('\n') : row.SrcDeviceObj }
        this.$refs['accountForm'].resetFields();
      })
      this.dialogVisible = true
    },
    deleteClick(tableData, index) {
      this.$confirm('此操作将永久删除该规则, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        tableData.splice(index, 1)
        const data = {
          Filter: {
            FileName: 'rule_net_in.json'
          },
          Data: {
            DefaultPolicy: this.DefaultPolicy,
            RuleData: [
              ...tableData
            ]
          }
        }
        const res = await connrequest('SetUICommonParam', data)
        if (res.Status.StatusCode === 0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    submit() {
      this.$refs['accountForm'].validate(async (valid) => {
        if (valid) {
          if (this.accountForm.SrcDeviceObjType === 2) {
            if (!this.accountForm.SrcDeviceObj || this.accountForm.SrcDeviceObj.length === 0) {
              this.$message.error('请选择源地址对象部门')
              return false
            }
          }
          if (this.accountForm.SrcDeviceObjType === 8) {
            if (!this.accountForm.SrcDeviceObj || this.accountForm.SrcDeviceObj.length === 0) {
              this.$message.error('请选择源地址对象角色')
              return false
            }
          }
          if (this.accountForm.SrcDeviceObjType === 6) {
            if (!this.accountForm.SrcDeviceObj || this.accountForm.SrcDeviceObj.length === 0) {
              this.$message.error('请选择源地址对象资产')
              return false
            }
          }
          if (this.accountForm.SrcDeviceObjType === 7) {
            if (!this.accountForm.SrcDeviceObj) {
              this.$message.error('指定网址或网段')
              return false
            } else if (!validateInput(this.accountForm.SrcDeviceObj)) {
              this.$message.error('请输入正确的地址或网段')
              return false
            }
          }
          if (this.accountForm.DstDeviceObjType === 2) {
            if (!this.accountForm.DstDeviceObj || this.accountForm.DstDeviceObj.length === 0) {
              this.$message.error('请选择应用对象部门')
              return false
            }
          }
          if (this.accountForm.DstDeviceObjType === 8) {
            if (!this.accountForm.DstDeviceObj || this.accountForm.DstDeviceObj.length === 0) {
              this.$message.error('请选择应用对象角色')
              return false
            }
          }
          if (this.accountForm.DstDeviceObjType === 6) {
            if (!this.accountForm.DstDeviceObj || this.accountForm.DstDeviceObj.length === 0) {
              this.$message.error('请选择应用对象资产')
              return false
            }
          }
          if
            (this.Action !== 2 && this.tableData.findIndex(item => item.RuleName === this.accountForm.RuleName) !== -1) {
            this.$message.error('该规则已经存在')
            return false
          }
          let data = {}
          if (this.Action === 1) {
            data = {
              Filter: {
                FileName: 'rule_net_in.json'
              },
              Data: {
                DefaultPolicy: this.DefaultPolicy,
                RuleData: [
                  ...this.tableData,
                  {
                    ...this.accountForm,
                    SrcDeviceObj: this.accountForm.SrcDeviceObjType === 7 ? this.accountForm.SrcDeviceObj.split(/[\r\n]+/).filter(line => line.trim() !== "") : this.accountForm.SrcDeviceObj,
                    RuleID: Math.floor(Date.now() / 1000)
                  }
                ]
              }
            }
          }
          if (this.Action === 2) {
            this.tableData[this.tableindex] = {
              ...this.accountForm,
              SrcDeviceObj: this.accountForm.SrcDeviceObjType === 7 ? this.accountForm.SrcDeviceObj.split(/[\r\n]+/).filter(line => line.trim() !== "") : this.accountForm.SrcDeviceObj,
            }
            data = {
              Filter: {
                FileName: 'rule_net_in.json'
              },
              Data: {
                DefaultPolicy: this.DefaultPolicy,
                RuleData: [
                  ...this.tableData
                ]
              }
            }
          }
          if (this.Action === 3) {
            this.tableData.splice(this.tableindex, 0, { ...this.accountForm, RuleID: Math.floor(Date.now() / 1000) })
            data = {
              Filter: {
                FileName: 'rule_net_in.json'
              },
              Data: {
                DefaultPolicy: this.DefaultPolicy,
                RuleData: [
                  ...this.tableData
                ]
              }
            }
          }
          const res = await connrequest('SetUICommonParam', data)
          if (res.Status.StatusCode === 0) {
            this.$message.success(this.Action == 1 ? '添加成功' : '修改成功')
            this.getData()
            this.dialogVisible = false
          }
        }
      })
    },
    async radioChange(row) {
      const data = {
        Filter: {
          FileName: 'rule_net_in.json'
        },
        Data: {
          DefaultPolicy: row,
          RuleData: this.tableData
        }
      }
      const res = await connrequest('SetUICommonParam', data)
      if (res.Status.StatusCode === 0) {
        this.$message.success('修改成功')
        this.getData()
      }
    },
  }
}
</script>